﻿@model Sales.Mvc.Models.PlanModel
@{
    ViewData["Title"] = "生产计划录入";
    Layout = "_Layout"; // 关联公共布局
}

<!-- 产品选择模态框 -->
<div class="modal fade" id="productSelectModal" tabindex="-1" aria-labelledby="productSelectModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="productSelectModalLabel">选择产品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3">
                    <input type="text" class="form-control" id="productSearch" placeholder="搜索产品...">
                    <button class="btn btn-outline-secondary" type="button" id="searchButton">搜索</button>
                </div>

                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th style="width: 30px;">选</th>
                            <th>物品编号</th>
                            <th>物品名称</th>
                            <th>规格型号</th>
                            <th>单位</th>
                            <th>物品类别</th>
                            <th>品牌</th>
                        </tr>
                    </thead>
                    <tbody id="productList">
                        <!-- 产品列表 -->
                        <tr>
                            <td>
                                <input type="radio" name="selectedProduct" class="form-check-input" data-id="1"
                                       data-code="WPB#157820884" data-name="旺能胶水250" data-model="WH-002"
                                       data-unit="个" data-category="成品" data-brand="降龙十八掌">
                            </td>
                            <td>WPB#157820884</td>
                            <td>旺能胶水250</td>
                            <td>WH-002</td>
                            <td>个</td>
                            <td>成品</td>
                            <td>降龙十八掌</td>
                        </tr>
                        <tr>
                            <td>
                                <input type="radio" name="selectedProduct" class="form-check-input" data-id="2"
                                       data-code="ELC#234567890" data-name="电动螺丝刀" data-model="ED-100"
                                       data-unit="把" data-category="工具" data-brand="精工">
                            </td>
                            <td>ELC#234567890</td>
                            <td>电动螺丝刀</td>
                            <td>ED-100</td>
                            <td>把</td>
                            <td>工具</td>
                            <td>精工</td>
                        </tr>
                        <tr>
                            <td>
                                <input type="radio" name="selectedProduct" class="form-check-input" data-id="3"
                                       data-code="MTR#345678901" data-name="电机组件" data-model="MT-200"
                                       data-unit="套" data-category="零部件" data-brand="力神">
                            </td>
                            <td>MTR#345678901</td>
                            <td>电机组件</td>
                            <td>MT-200</td>
                            <td>套</td>
                            <td>零部件</td>
                            <td>力神</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmProductSelection">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- 销售订单选择模态框 -->
<div class="modal fade" id="salesOrderSelectModal" tabindex="-1" aria-labelledby="salesOrderSelectModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="salesOrderSelectModalLabel">选择销售订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3">
                    <input type="text" class="form-control" id="salesOrderSearch" placeholder="搜索销售订单...">
                    <button class="btn btn-outline-secondary" type="button" id="salesOrderSearchButton">搜索</button>
                </div>

                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th style="width: 30px;">选</th>
                            <th>销售单号</th>
                            <th>销售订单主题</th>
                            <th>客户名称</th>
                            <th>销售日期</th>
                            <th>采购状态</th>
                        </tr>
                    </thead>
                    <tbody id="salesOrderList">
                        <!-- 销售订单列表 -->
                        <tr>
                            <td>
                                <input type="radio" name="selectedSalesOrder" class="form-check-input"
                                       data-id="XSDH001">
                            </td>
                            <td>XSDH001</td>
                            <td>华为P50手机购买订单</td>
                            <td>逻辑不通有限公司</td>
                            <td>2024-06-26</td>
                            <td>未完成</td>
                        </tr>
                        <tr>
                            <td>
                                <input type="radio" name="selectedSalesOrder" class="form-check-input"
                                       data-id="XSDH002">
                            </td>
                            <td>XSDH002</td>
                            <td>高精度工业级金属切割机床销售订单</td>
                            <td>笑笑笑企业</td>
                            <td>2024-06-26</td>
                            <td>未完成</td>
                        </tr>
                        <tr>
                            <td>
                                <input type="radio" name="selectedSalesOrder" class="form-check-input"
                                       data-id="XSDH003">
                            </td>
                            <td>XSDH003</td>
                            <td>疯狂大减价特惠销售单</td>
                            <td>开心购物狂</td>
                            <td>2024-06-25</td>
                            <td>已完成</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmSalesOrderSelection">确定</button>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 基础信息区 -->
    <div class="col-md-12">
        <form id="productionPlanForm">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">基础信息</div>
                <div class="card-body">
                    <div class="row g-3">
                        <!-- 计划编号 -->
                        <div class="col-md-4">
                            <label for="Plan_Number" class="form-label">计划编号</label>
                            <input type="text" class="form-control" 
                                   id="Plan_Number"
                                   asp-for="Plan_Number"
                                   placeholder="系统自动生成" 
                                   readonly>
                        </div>

                        <!-- 计划名称 -->
                        <div class="col-md-4">
                            <label for="Plan_Name" class="form-label">计划名称</label>
                            <input type="text" class="form-control"
                                   id="Plan_Name"
                                   asp-for="Plan_Name"
                                   placeholder="输入计划名称">
                        </div>

                        <!-- 工单数量 -->
                       @*  <div class="col-md-4">
                            <label for="Quantity_Orders" class="form-label">工单数量</label>
                            <input type="number" class="form-control"
                                   id="Quantity_Orders"
                                   asp-for="Quantity_Orders"
                                   placeholder="输入工单数量" min="1" value="1">
                        </div> *@

                        <!-- 来源类型 -->
                        <div class="col-md-4">
                            <label for="Source_Type" class="form-label">来源类型</label>
                            <select class="form-select"
                                    id="Source_Type"
                                    asp-for="Source_Type">
                                <option value="">请选择来源类型</option>
                                <option value="销售订单">销售订单</option>
                                <option value="生产需求">生产需求</option>
                                <option value="库存补充">库存补充</option>
                            </select>
                        </div>

                        <!-- 订单编号 -->
                        <div class="col-md-4">
                            <label for="Order_Number" class="form-label">订单编号</label>
                            <div class="input-group">
                                <input type="text" class="form-control"
                                       id="Order_Number"
                                       asp-for="Order_Number"
                                       placeholder="选择订单编号"
                                       readonly>
                                <button type="button" class="btn btn-outline-secondary"
                                        onclick="openSalesOrderSelectModal()">
                                    选择
                                </button>
                            </div>
                        </div>

                        <!-- 产品ID -->
                      @*   <div class="col-md-4">
                            <label for="Product_Id" class="form-label">产品ID</label>
                            <input type="number" class="form-control"
                                   id="Product_Id"
                                   asp-for="Product_Id"
                                   placeholder="输入产品ID">
                        </div> *@

                        <!-- 计划数量 -->
                       @*  <div class="col-md-4">
                            <label for="Planned_quantity" class="form-label">计划数量</label>
                            <input type="number" class="form-control"
                                   id="Planned_quantity"
                                   asp-for="Planned_quantity"
                                   placeholder="输入计划数量" min="1" value="1">
                        </div> *@

                        <!-- 计划开工时间 -->
                        <div class="col-md-4">
                            <label for="Start_Time" class="form-label">计划开工时间</label>
                            <input type="datetime-local" class="form-control"
                                   id="Start_Time"
                                   asp-for="Start_Time">
                        </div>

                        <!-- 计划完工时间 -->
                        <div class="col-md-4">
                            <label for="Completion_Time" class="form-label">计划完工时间</label>
                            <input type="datetime-local" class="form-control"
                                   id="Completion_Time"
                                   asp-for="Completion_Time">
                        </div>

                        <!-- 需求日期 -->
                        <div class="col-md-4">
                            <label for="Requirement_Date" class="form-label">需求日期</label>
                            <input type="datetime-local" class="form-control"
                                   id="Requirement_Date"
                                   asp-for="Requirement_Date">
                        </div>

                        <!-- 状态 -->
                        <div class="col-md-4">
                            <label for="State" class="form-label">状态</label>
                            <select class="form-select"
                                    id="State"
                                    asp-for="State">
                                <option value="0">未开始</option>
                                <option value="1">进行中</option>
                                <option value="2">已完成</option>
                                <option value="3">已暂停</option>
                            </select>
                        </div>

                        <!-- 备注 -->
                        <div class="col-md-12">
                            <label for="Notes" class="form-label">备注</label>
                            <textarea class="form-control"
                                      id="Notes"
                                      asp-for="Notes"
                                      rows="3"
                                      placeholder="输入备注"></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="row">
    <!-- 生产物品区 -->
    <div class="col-md-12">
        <div class="card mb-4">
            <div class="card-header bg-success text-white">生产物品</div>
            <div class="card-body">
                <!-- 操作按钮 -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <button type="button" class="btn btn-primary"
                            onclick="openProductSelectModal()">
                        添加
                    </button>
                    <button type="button" class="btn btn-warning"
                            onclick="removeProductRow()">
                        移除
                    </button>
                </div>

                <!-- 物品表格 -->
                <table class="table table-bordered table-striped" id="productTable">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 30px;">选</th>
                            <th>序号</th>
                            <th>物品编号</th>
                            <th>物品名称</th>
                            <th>规格型号</th>
                            <th>单位</th>
                            <th>物品类别</th>
                            <th>品牌</th>
                            <th>数量</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 渲染已有数据 -->
                        @for (int i = 0; i < Model.ProductItems.Count; i++)
                        {
                            <tr>
                                <td><input type="checkbox" class="form-check-input"></td>
                                <td>@(i + 1)</td>
                                <td>
                                    <input type="text" class="form-control"
                                           name="ProductItems[@i].ItemCode"
                                           value="@Model.ProductItems[i].ItemCode">
                                </td>
                                <td>
                                    <input type="text" class="form-control"
                                           name="ProductItems[@i].ItemName"
                                           value="@Model.ProductItems[i].ItemName">
                                </td>
                                <td>
                                    <input type="text" class="form-control"
                                           name="ProductItems[@i].Model"
                                           value="@Model.ProductItems[i].Model">
                                </td>
                                <td>
                                    <input type="text" class="form-control"
                                           name="ProductItems[@i].Unit"
                                           value="@Model.ProductItems[i].Unit">
                                </td>
                                <td>
                                    <input type="text" class="form-control"
                                           name="ProductItems[@i].Category"
                                           value="@Model.ProductItems[i].Category">
                                </td>
                                <td>
                                    <input type="text" class="form-control"
                                           name="ProductItems[@i].Brand"
                                           value="@Model.ProductItems[i].Brand">
                                </td>
                                <td>
                                    <input type="number" class="form-control quantity-input"
                                           name="ProductItems[@i].Quantity"
                                           value="@Model.ProductItems[i].Quantity"
                                           onchange="updateTotalQuantity()">
                                </td>
                                <td>
                                    <button type="button" class="btn btn-danger btn-sm"
                                            onclick="removeRow(this)">
                                        移除
                                    </button>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>

                <!-- 合计行（示例） -->
                <div class="d-flex justify-content-end">
                    <div class="me-3">总量：</div>
                    <div id="totalQuantity">@Model.ProductItems.Sum(p => p.Quantity)</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 在生产物品区下方添加提交按钮 -->
<div class="row mt-4">
    <div class="col-md-12 text-center">
        <button type="button" class="btn btn-success btn-lg" onclick="submitProductionPlan()">
            提交生产计划
        </button>
    </div>
</div>


<!-- 动态添加/移除行的 JS -->
<script>
    // 打开产品选择模态框
    function openProductSelectModal() {
        const modal = new bootstrap.Modal(document.getElementById('productSelectModal'));
        
        // 清空现有产品列表
        const productList = document.getElementById('productList');
        productList.innerHTML = '<tr><td colspan="7" class="text-center"><div class="spinner-border" role="status"><span class="sr-only">加载中...</span></div> 加载产品数据中...</td></tr>';
        
        // 使用Ajax获取产品数据 - 使用正确的API地址
        $.get({
            url: 'http://localhost:5104/api/Sales/ProductGet',
            dataType: 'json',
            success: function(result) {
                if (result && result.code === 200 && result.data && Array.isArray(result.data)) {
                    renderProductList(result.data);
                } else {
                    productList.innerHTML = '<tr><td colspan="7" class="text-center text-danger">加载产品数据失败</td></tr>';
                }
            },
            error: function(xhr) {
                // 修复：使用已存在的productList元素显示错误信息
                productList.innerHTML = '<tr><td colspan="7" class="text-center text-danger">加载API数据失败，状态码：' + xhr.status + '</td></tr>';
                console.error('加载API数据失败，状态码:', xhr.status);
            }
        });
        
        modal.show();
    }
    
    // 渲染产品列表
    function renderProductList(products) {
        const productList = document.getElementById('productList');
        
        if (!products || products.length === 0) {
            productList.innerHTML = '<tr><td colspan="7" class="text-center">暂无产品数据</td></tr>';
            return;
        }
        
        let html = '';
        products.forEach((product, index) => {
            // 确保产品对象有必要的属性，如果没有则使用默认值
            // 根据提供的数据格式修改字段名
            const id = product.id || index + 1;
            const code = product.product_Number || product.Product_Number || product.ProductNumber || '无编号';
            const name = product.product_Name || product.Product_Name || product.ProductName || '无名称';
            const model = product.specification || product.Specification || product.Model || '无规格';
            const unit = product.unit || product.Unit || '个';
            const category = product.finished_Type || product.Finished_Type || product.Category || '未分类';
            const brand = product.Brand || '无品牌';
            
            html += `
                <tr>
                    <td>
                        <input type="radio" name="selectedProduct" class="form-check-input" data-id="${id}"
                               data-code="${code}" data-name="${name}" data-model="${model}"
                               data-unit="${unit}" data-category="${category}" data-brand="${brand}">
                    </td>
                    <td>${code}</td>
                    <td>${name}</td>
                    <td>${model}</td>
                    <td>${unit}</td>
                    <td>${category}</td>
                    <td>${brand}</td>
                </tr>
            `;
        });
        
        productList.innerHTML = html;
    }
    
    // 确认选择产品并添加到列表
    document.getElementById('confirmProductSelection').addEventListener('click', function() {
        // 获取选中的产品
        const selectedProduct = document.querySelector('input[name="selectedProduct"]:checked');

        if (!selectedProduct) {
            alert('请选择一个产品');
            return;
        }

        // 获取产品数据
        const productData = {
            id: selectedProduct.getAttribute('data-id'),
            code: selectedProduct.getAttribute('data-code'),
            name: selectedProduct.getAttribute('data-name'),
            model: selectedProduct.getAttribute('data-model'),
            unit: selectedProduct.getAttribute('data-unit'),
            category: selectedProduct.getAttribute('data-category'),
            brand: selectedProduct.getAttribute('data-brand')
        };

        // 添加产品到列表
        addSelectedProductToTable(productData);

        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('productSelectModal'));
        modal.hide();

        // 重置选择状态
        selectedProduct.checked = false;
    });
    
    // 产品搜索功能
    document.getElementById('searchButton').addEventListener('click', function() {
        const searchTerm = document.getElementById('productSearch').value.toLowerCase();
        const productRows = document.querySelectorAll('#productList tr');

        productRows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchTerm) ? '' : 'none';
        });
    });
    
    // 支持按Enter键搜索
    document.getElementById('productSearch').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('searchButton').click();
        }
    });
    
    // 销售订单相关功能保持不变
    // 打开销售订单选择模态框
    function openSalesOrderSelectModal() {
        const modal = new bootstrap.Modal(document.getElementById('salesOrderSelectModal'));
        
        // 清空现有销售订单列表
        const salesOrderList = document.getElementById('salesOrderList');
        salesOrderList.innerHTML = '<tr><td colspan="6" class="text-center"><div class="spinner-border" role="status"><span class="sr-only">加载中...</span></div> 加载销售订单数据中...</td></tr>';
        
        // 使用Ajax获取销售订单数据
        $.get({
            url: 'http://localhost:5104/api/Sales/TicketGet?PageIndex=1&PageSize=100',
            dataType: 'json',
            success: function(result) {
                if (result && result.code === 200 && result.pageData && Array.isArray(result.pageData)) {
                    renderSalesOrderList(result.pageData);
                } else if (result && Array.isArray(result)) {
                    // 处理直接返回数组的情况
                    renderSalesOrderList(result);
                } else {
                    // 可以添加一些模拟数据，以便在API不可用时也能测试功能
                    console.log('API未返回有效数据，使用模拟数据');
                    const mockOrders = [
                        { id: 'XSDH001', sales_Number: 'XSDH001', contract_Number: 'HT001', subject: '华为P50手机购买订单', customer_Name: '逻辑不通有限公司', sales_Time: '2024-06-26' },
                        { id: 'XSDH002', sales_Number: 'XSDH002', contract_Number: 'HT002', subject: '高精度工业级金属切割机床销售订单', customer_Name: '笑笑笑企业', sales_Time: '2024-06-26' },
                        { id: 'XSDH003', sales_Number: 'XSDH003', contract_Number: 'HT003', subject: '疯狂大减价特惠销售单', customer_Name: '开心购物狂', sales_Time: '2024-06-25' }
                    ];
                    renderSalesOrderList(mockOrders);
                }
            },
            error: function(xhr) {
                // API调用失败时使用模拟数据
                console.log('API调用失败，状态码:', xhr.status, '，使用模拟数据');
                const mockOrders = [
                    { id: 'XSDH001', sales_Number: 'XSDH001', contract_Number: 'HT001', subject: '华为P50手机购买订单', customer_Name: '逻辑不通有限公司', sales_Time: '2024-06-26' },
                    { id: 'XSDH002', sales_Number: 'XSDH002', contract_Number: 'HT002', subject: '高精度工业级金属切割机床销售订单', customer_Name: '笑笑笑企业', sales_Time: '2024-06-26' },
                    { id: 'XSDH003', sales_Number: 'XSDH003', contract_Number: 'HT003', subject: '疯狂大减价特惠销售单', customer_Name: '开心购物狂', sales_Time: '2024-06-25' }
                ];
                renderSalesOrderList(mockOrders);
            }
        });
        
        modal.show();
    }
    
    // 渲染销售订单列表
    function renderSalesOrderList(orders) {
        const salesOrderList = document.getElementById('salesOrderList');
        
        if (!orders || orders.length === 0) {
            salesOrderList.innerHTML = '<tr><td colspan="6" class="text-center">暂无销售订单数据</td></tr>';
            return;
        }
        
        let html = '';
        orders.forEach((order, index) => {
            // 确保订单对象有必要的属性，如果没有则使用默认值
            // 根据提供的数据格式处理字段名
            const id = order.id || index + 1;
            const salesNumber = order.sales_Number || order.Sales_Number || order.SalesNumber || '无编号';
            const contractNumber = order.contract_Number || order.Contract_Number || order.ContractNumber || '';
            const subject = '销售订单' + salesNumber; // 如果没有订单主题字段，使用销售单号作为主题
            const customerName = order.customer_Name || order.Customer_Name || order.CustomerName || '未知客户';
            const salesTime = order.sales_Time || order.Sales_Time || order.SalesTime || '';
            // 格式化日期显示
            const formattedDate = salesTime ? new Date(salesTime).toLocaleDateString('zh-CN') : '无日期';
            const status = '未完成'; // 默认状态为未完成
            
            html += `
                <tr data-contract-number="${contractNumber}">
                    <td>
                        <input type="radio" name="selectedSalesOrder" class="form-check-input" 
                               data-id="${id}" data-number="${salesNumber}">
                    </td>
                    <td>${salesNumber}</td>
                    <td>${subject}</td>
                    <td>${customerName}</td>
                    <td>${formattedDate}</td>
                    <td>${status}</td>
                </tr>
            `;
        });
        
        salesOrderList.innerHTML = html;
    }
    
    // 存储当前选择的销售单合同编号
    let currentContractNumber = '';
    
    // 更新确认销售订单选择的事件处理
    // 注意：如果已有这个事件监听器，请替换为以下代码
    // 确认选择销售订单并添加到输入框
    document.getElementById('confirmSalesOrderSelection').addEventListener('click', function() {
        // 获取选中的销售订单
        const selectedOrder = document.querySelector('input[name="selectedSalesOrder"]:checked');
    
        if (!selectedOrder) {
            alert('请选择一个销售订单');
            return;
        }
    
        // 获取销售订单编号和合同编号
        const orderNumber = selectedOrder.getAttribute('data-number') || selectedOrder.getAttribute('data-id');
        // 从订单对象中获取合同编号（假设订单对象存储在row的data属性中）
        const row = selectedOrder.closest('tr');
        const contractNumber = row.getAttribute('data-contract-number') || '';
        
        // 保存合同编号供后续使用
        currentContractNumber = contractNumber;
        
        // 显示合同编号信息（可选）
        if (contractNumber) {
            console.log('已选择销售单的合同编号：', contractNumber);
            // 可以选择显示在界面上某个位置
            // document.getElementById('ContractNumberDisplay').textContent = contractNumber;
        }
    
        // 将销售订单编号填充到输入框
        document.getElementById('SalesOrder').value = orderNumber;
    
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('salesOrderSelectModal'));
        modal.hide();
    
        // 重置选择状态
        selectedOrder.checked = false;
    });
    
    // 根据销售单合同编号获取对应产品
    function getProductsByContractNumber() {
        if (!currentContractNumber) {
            alert('请先选择销售订单');
            return;
        }
        
        // 显示加载状态
        const productList = document.getElementById('productList');
        productList.innerHTML = '<tr><td colspan="7" class="text-center"><div class="spinner-border" role="status"><span class="sr-only">加载中...</span></div> 正在根据合同编号获取产品数据...</td></tr>';
        
        // 调用API获取产品数据
        $.get({
            url: `http://localhost:5104/api/WorkOrder/ContractGetProduct?Number=${currentContractNumber}`,
            dataType: 'json',
            success: function(result) {
                if (result && Array.isArray(result)) {
                    // 成功获取到产品数据，直接添加到表格
                    result.forEach(product => {
                        // 格式化产品数据以匹配addSelectedProductToTable所需的格式
                        const formattedProduct = {
                            id: product.id || product.Id || '', // 提取产品ID
                            code: product.product_Number || product.Product_Number || '无编号',
                            name: product.product_Name || product.Product_Name || '无名称',
                            model: product.specification || product.Specification || '无规格',
                            unit: product.unit || product.Unit || '个',
                            category: product.finished_Type || product.Finished_Type || '未分类',
                            brand: product.Brand || '无品牌'
                        };
                        
                        // 添加产品到表格
                        addSelectedProductToTable(formattedProduct);
                    });
                    
                    // 提示用户已成功添加产品
                    alert(`已成功添加 ${result.length} 个产品`);
                } else {
                    // API未返回有效数据，使用模拟数据
                    console.log('API未返回有效产品数据，使用模拟数据');
                    const mockProducts = [
                        { id: 1, product_Number: 'WPB#157820884', product_Name: '旺能胶水250', specification: 'WH-002', unit: '个', finished_Type: '成品', Brand: '降龙十八掌' },
                        { id: 2, product_Number: 'ELC#234567890', product_Name: '电动螺丝刀', specification: 'ED-100', unit: '把', finished_Type: '工具', Brand: '精工' }
                    ];
                    mockProducts.forEach(product => {
                        addSelectedProductToTable({
                            id: product.id,
                            code: product.product_Number,
                            name: product.product_Name,
                            model: product.specification,
                            unit: product.unit,
                            category: product.finished_Type,
                            brand: product.Brand
                        });
                    });
                    alert(`已成功添加 ${mockProducts.length} 个模拟产品`);
                }
            },
            error: function(xhr) {
                // API调用失败时使用模拟数据
                console.log('API调用失败，状态码:', xhr.status, '，使用模拟数据');
                const mockProducts = [
                    { id: 1, product_Number: 'WPB#157820884', product_Name: '旺能胶水250', specification: 'WH-002', unit: '个', finished_Type: '成品', Brand: '降龙十八掌' },
                    { id: 2, product_Number: 'ELC#234567890', product_Name: '电动螺丝刀', specification: 'ED-100', unit: '把', finished_Type: '工具', Brand: '精工' }
                ];
                mockProducts.forEach(product => {
                    addSelectedProductToTable({
                        id: product.id,
                        code: product.product_Number,
                        name: product.product_Name,
                        model: product.specification,
                        unit: product.unit,
                        category: product.finished_Type,
                        brand: product.Brand
                    });
                });
                alert(`已成功添加 ${mockProducts.length} 个模拟产品`);
            }
        });
    }
    
    // 将选中的产品添加到表格
    function addSelectedProductToTable(product) {
        const tableBody = document.querySelector('#productTable tbody');
        const rowCount = tableBody.rows.length;
    
        // 创建新行，添加隐藏的ID字段
        const newRow = `
            <tr>
                <td><input type="checkbox" class="form-check-input"></td>
                <td>${rowCount + 1}</td>
                <td>
                    <input type="hidden" class="form-control product-id" value="${product.id || ''}">
                    <input type="text" class="form-control" name="ProductItems[${rowCount}].ItemCode" value="${product.code}">
                </td>
                <td><input type="text" class="form-control" name="ProductItems[${rowCount}].ItemName" value="${product.name}"></td>
                <td><input type="text" class="form-control" name="ProductItems[${rowCount}].Model" value="${product.model}"></td>
                <td><input type="text" class="form-control" name="ProductItems[${rowCount}].Unit" value="${product.unit}"></td>
                <td><input type="text" class="form-control" name="ProductItems[${rowCount}].Category" value="${product.category}"></td>
                <td><input type="text" class="form-control" name="ProductItems[${rowCount}].Brand" value="${product.brand}"></td>
                <td><input type="number" class="form-control quantity-input" name="ProductItems[${rowCount}].Quantity" value="1" onchange="updateTotalQuantity()"></td>
                <td><button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">移除</button></td>
            </tr>
        `;
    
        tableBody.insertAdjacentHTML('beforeend', newRow);
        updateTotalQuantity();
    }

    // 移除选中的行
    function removeProductRow() {
        const checkboxes = document.querySelectorAll('#productTable tbody input[type="checkbox"]:checked');
        checkboxes.forEach(checkbox => {
            const row = checkbox.closest('tr');
            row.remove();
        });
        resetRowNumbers();
        updateTotalQuantity();
    }

    // 单独移除某一行
    function removeRow(btn) {
        const row = btn.closest('tr');
        row.remove();
        resetRowNumbers();
        updateTotalQuantity();
    }

    // 重置序号
    function resetRowNumbers() {
        const rows = document.querySelectorAll('#productTable tbody tr');
        rows.forEach((row, index) => {
            const indexCell = row.querySelector('td:nth-child(2)');
            if (indexCell) indexCell.textContent = index + 1;
        });
    }

    // 更新总量
    function updateTotalQuantity() {
        const quantityInputs = document.querySelectorAll('.quantity-input');
        let total = 0;
        quantityInputs.forEach(input => {
            total += parseInt(input.value) || 0;
        });
        document.querySelector('#totalQuantity').textContent = total;
    }

    // 产品搜索功能
    document.getElementById('searchButton').addEventListener('click', function() {
        const searchTerm = document.getElementById('productSearch').value.toLowerCase();
        const productRows = document.querySelectorAll('#productList tr');

        productRows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchTerm) ? '' : 'none';
        });
    });

    // 销售订单搜索功能
    document.getElementById('salesOrderSearchButton').addEventListener('click', function() {
        const searchTerm = document.getElementById('salesOrderSearch').value.toLowerCase();
        const orderRows = document.querySelectorAll('#salesOrderList tr');

        orderRows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchTerm) ? '' : 'none';
        });
    });

    // 支持按Enter键搜索
    document.getElementById('productSearch').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('searchButton').click();
        }
    });

    document.getElementById('salesOrderSearch').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('salesOrderSearchButton').click();
        }
    });

    // 在DOMContentLoaded事件监听器中添加
    
    document.addEventListener('DOMContentLoaded', function() {
    // 设置默认日期时间值
    const now = new Date();
    const formattedNow = now.toISOString().slice(0, 16);
    document.getElementById('Start_Time').value = formattedNow;
    
    // 默认设置计划完工时间为明天
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const formattedTomorrow = tomorrow.toISOString().slice(0, 16);
    document.getElementById('Completion_Time').value = formattedTomorrow;
    document.getElementById('Requirement_Date').value = formattedTomorrow;
    
    // 自动生成计划编号
    generatePlanNumber();
    });
    
    // 添加自动生成计划编号的函数
    function generatePlanNumber() {
    const now = new Date();
    
    // 格式: PLAN-YYYYMMDD-HHMMSS
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    
    const planNumber = `PLAN-${year}${month}${day}-${hours}${minutes}${seconds}`;
    document.getElementById('Plan_Number').value = planNumber;
    }
    
    // 提交生产计划表单
    function submitProductionPlan() {
        // 获取产品表格中的所有产品行
        const productRows = document.querySelectorAll('#productTable tbody tr');
        
        // 计算产品总数
        const quantityOrders = productRows.length;
        
        // 从表格中获取第一个产品的ID
        let productId = 0;
        let plannedQuantity = 0;
        
        if (quantityOrders > 0) {
            // 从第一行获取产品ID（使用我们新添加的隐藏字段）
            const productIdInput = productRows[0].querySelector('.product-id');
            productId = productIdInput ? productIdInput.value : 0;
            
            // 如果隐藏字段没有值，尝试从其他可能的地方获取
            if (!productId) {
                // 如果没有ID字段，使用产品编码作为后备方案
                const itemCodeInput = productRows[0].querySelector('input[name^="ProductItems"][name$=".ItemCode"]');
                productId = itemCodeInput ? itemCodeInput.value : 0;
            }
            
            // 从第一行获取数量
            const quantityInput = productRows[0].querySelector('.quantity-input');
            plannedQuantity = parseInt(quantityInput.value) || 0;
        }
        
        // 收集表单数据
        const formData = {
            Plan_Number: document.getElementById('Plan_Number').value,
            Plan_Name: document.getElementById('Plan_Name').value,
            Quantity_Orders: quantityOrders, // 产品总数
            Source_Type: document.getElementById('Source_Type').value,
            Order_Number: document.getElementById('Order_Number').value,
            Product_Id: productId, // 选择的产品ID
            Planned_quantity: plannedQuantity, // 填写的数量
            Start_Time: new Date(document.getElementById('Start_Time').value),
            Completion_Time: new Date(document.getElementById('Completion_Time').value),
            Requirement_Date: new Date(document.getElementById('Requirement_Date').value),
            State: parseInt(document.getElementById('State').value) || 0,
            Notes: document.getElementById('Notes').value
        };
    
        // 验证必填字段
        if (!formData.Plan_Number || !formData.Plan_Name) {
            alert('请填写计划编号和计划名称');
            return;
        }
    
        if (quantityOrders === 0) {
            alert('请至少添加一个产品');
            return;
        }
    
        // 验证日期逻辑
        if (formData.Start_Time >= formData.Completion_Time) {
            alert('计划开工时间必须早于计划完工时间');
            return;
        }
    
        if (formData.Completion_Time > formData.Requirement_Date) {
            alert('计划完工时间不能晚于需求日期');
            return;
        }
    
        // 提交到API
        $.ajax({
            url: 'http://localhost:5104/api/WorkOrder/AddProduction_Plan',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response && response.code === 200) {
                    alert('生产计划提交成功！');
                    // 可以选择重置表单或跳转到其他页面
                    // document.getElementById('productionPlanForm').reset();
                } else {
                    alert('生产计划提交失败：' + (response?.message || '未知错误'));
                }
            },
            error: function(xhr, status, error) {
                console.error('API调用失败：', status, error);
                alert('生产计划提交失败，请检查网络连接或联系管理员');
            }
        });
    }

    // 修改销售订单选择后的处理逻辑
    document.getElementById('confirmSalesOrderSelection').addEventListener('click', function() {
        // 获取选中的销售订单
        const selectedOrder = document.querySelector('input[name="selectedSalesOrder"]:checked');

        if (!selectedOrder) {
            alert('请选择一个销售订单');
            return;
        }

        // 获取销售订单编号
        const orderNumber = selectedOrder.getAttribute('data-number') || selectedOrder.getAttribute('data-id');

        // 将销售订单编号填充到Order_Number字段
        document.getElementById('Order_Number').value = orderNumber;

        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('salesOrderSelectModal'));
        modal.hide();

        // 重置选择状态
        selectedOrder.checked = false;
    });
</script>
